package com.training.java.redbox.struts.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.training.java.redbox.struts.domain.DAOException;
import com.training.java.redbox.struts.domain.Movie;
import com.training.java.redbox.struts.domain.MovieDAO;
import com.training.java.redbox.struts.domain.MovieDAOJDBCImpl;
import com.training.java.redbox.struts.domain.MovieService;
import com.training.java.redbox.struts.domain.ServiceException;

public class CheckOutAction  extends Action{

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		ServletContext servletContext =servlet.getServletContext();
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		MovieService movieService = context.getBean(MovieService.class);
		
		HttpSession session = request.getSession();
		List<Long> ids = (List<Long>) session.getAttribute("cart");
		
		List<Movie> movies = new ArrayList<>();
		
		//MovieDAO dao = new MovieDAOJDBCImpl();
		
		for(long id : ids)
		{
			try {
				movies.add(movieService.findByMovieId(id));
			} catch (ServiceException e) {
				e.printStackTrace();
			}
		}
		
		request.setAttribute("MoviesCart", movies);
		session.setAttribute("MoviesCart", movies);

		
		return mapping.findForward("finalcheckout");
	}
}
